﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Events;
using Elvex;

namespace Elvex
{
    using MessageQueue = Queue<KeyValuePair<NetSession, byte[]>>;

    class NetMessage
    {
        public NetSession Session { get; set; }

        public byte[] Message { get; set; }
    }

    public class NetManager : MonoSingleton<NetManager>
    {
        private List<NetSession> Sessions { get; } = new List<NetSession>();
        
        private MessageQueue Messages { get; set; } = new MessageQueue();

        private void Awake()
        {
            DontDestroyOnLoad(gameObject);
        }

        public void AddSession(NetSession session)
        {
            Sessions.Add(session);
        }

        public void AddMessage(NetSession session, byte[] buffer)
        {
            Messages.Enqueue(new KeyValuePair<NetSession, byte[]>(session, buffer));
        }

        public static NetSession CreateSession(Socket socket)
        {
            //NetSession session = new NetSession(socket);
            //session.Protocol.OnReceive = (buffer) => { Instance.OnReceive(session, buffer); };
            //Instance.Sessions.Add(session);
            //return session;

            return null;
        }

        private void Update()
        {
            MessageQueue queue = Messages;
            Messages = new MessageQueue();
            foreach ( var item in queue)
            {
                item.Key.OnReceive?.Invoke(item.Value);
            }
        }
    }
}
